<template>
  <div class="">
    <el-form :model="detailForm" ref="detailForm" :rules="rules" :label-position="labelPosition">
      <el-card class="box-card" shadow="never">
        <div slot="header" class="header-card">
          <span class="header-card-title">上牌信息</span>
        </div>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="合计费用:">
              <el-input disabled v-if="isEdit" v-model="detailForm.sumPrice"
                        placeholder="验车费用+上牌费用+拍照邮寄费用"/>
              <span v-else>{{ detailForm.sumPrice }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="验车费用:" prop="checkCarPrice">
              <el-input v-if="isEdit" v-model="detailForm.checkCarPrice" placeholder="输入验车费用"
                        @change="changeAmount('checkCarPrice')"></el-input>
              <span v-else>{{ detailForm.checkCarPrice }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上牌费用:" prop="registerPrice">
              <el-input v-if="isEdit" v-model="detailForm.registerPrice" placeholder="输入上牌费用"
                        @change="changeAmount('registerPrice')"></el-input>
              <span v-else>{{ detailForm.registerPrice }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="牌照邮寄费用:" prop="photoMailPrice">
              <el-input v-if="isEdit" v-model="detailForm.photoMailPrice" placeholder="输入牌照邮寄费用"
                        @change="changeAmount('photoMailPrice')"></el-input>
              <span v-else>{{ detailForm.photoMailPrice }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否限牌城市:" prop="isLimitCity">
              <el-select v-model="detailForm.isLimitCity" placeholder="选择是否限牌城市" style="width: 100%;"
                         v-if="isEdit" @change="handleChange">
                <el-option v-for="v in limitCity" :label="v.label" :value="v.value" :key="v.value"></el-option>

              </el-select>
              <span v-else> {{ selectDictLabel(limitCity, detailForm.isLimitCity) }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8" v-if="isBool">
            <el-form-item label="指标所属城市:" prop="indexBelongCity">

              <city-select v-model="citySelection" placeholder="请选择指标所属城市" ref="citySelect"
                           @change="citySelectionChange" v-if="isEdit"></city-select>

              <span v-else>{{ detailForm.indexBelongCity }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8" v-if="isBool">
            <el-form-item label="指标类型:" prop="indexType"
                          :rules="{required:isBool, message: '请选择指标类型', trigger: 'change'}">
              <el-select v-model="detailForm.indexType" placeholder="选择指标类型" style="width: 100%;" v-if="isEdit">
                <el-option label="燃油" value="1">
                </el-option>
                <el-option label="新能源" value="2">
                </el-option>
              </el-select>

              <span v-else>{{ selectDictLabel(dict.type.online_offline, detailForm.indexType) }} </span>

            </el-form-item>

          </el-col>
          <el-col :span="8">
            <el-form-item label="付款类型:" prop="payType"
                          :rules="{required:isBool, message: '请选择付款类型', trigger: 'change'}">
              <el-select v-model="detailForm.payType" placeholder="选择付款类型" style="width: 100%;" v-if="isEdit">

                <el-option v-for="item in payTypeList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>

              <span v-else> {{ selectDictLabel(payTypeList, detailForm.payType) }}</span>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="备注:" prop="remark">
              <el-input v-if="isEdit" placeholder="请输入备注" type="textarea" :rows="4"
                        :maxlength="500" v-model="detailForm.remark"></el-input>
              <span v-else style="margin: 0;">{{ detailForm.remark }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
  </div>
</template>

<script>
import citySelect from "@/views/cwgd/components/citySelect/index.vue";
import {getInfoByCityIdAndType} from "@/api/cwgd/registrationApi.js";
import {toNumberAdd} from "@/utils/utils"

export default {
  name: 'brandInfo',
  dicts: ['work_order_type', 'online_offline'],
  components: {citySelect},
  props: {
    value: {
      type: Object,
      default: {},
    },
    isEdit: {
      type: Boolean,
      default: true,
    }
  },
  computed: {
    detailForm: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            that.$emit("input", {...target, [key]: value});
            return true;
          },
        });
        return proxy;
      },
    },
    labelPosition() {
      if (this.isEdit) {
        return 'top'
      } else {
        return 'right'
      }
    },
    selectDictLabel() {
      return function (list, value) {
        let index = list.findIndex(a => a.value == value)
        if (index !== -1) {
          return list[index].label
        }
      }
    }
  },
  watch: {
    'value.sumPrice': {
      handler(val) {
        if (!val) {
          this.handleSumPrice()
        }
      },
      immediate: true
    }
  },
  data() {
    var city = async (rule, value, callback) => {
      let that = this
      if (value === '') {
        return callback(new Error('指标所属城市能为空'));
      } else {
        let obj = {
          cityId: that.detailForm.indexBelongCityId,
          type: that.detailForm.isLimitCity
        }
        const res = await getInfoByCityIdAndType(obj)
        if (res === false) {
          callback(new Error('所选城市没有指标类型'));
        } else {
          callback()
        }
      }
    }
    return {
      isBool: false,
      // sumPrice: 0,
      citySelection: [],
      payTypeList: [{value: '1', label: '车管垫付，走报销，月结'}, {value: '2', label: '公对公'}],
      limitCity: [{value: 1, label: '是'}, {value: 2, label: '否'}],
      rules: {
        checkCarPrice: [
          {required: this.isEdit, message: '请输入验车费用', trigger: 'blur'},
        ],
        registerPrice: [
          {required: this.isEdit, message: '请输入上牌费用', trigger: 'blur'},
        ],
        photoMailPrice: [
          {required: this.isEdit, message: '请输入牌照邮费用', trigger: 'blur'},
        ],
        isLimitCity: [
          {required: this.isEdit, message: '请选择是否限牌城市', trigger: 'change'},
        ],
        indexBelongCity: [
          {required: this.isEdit, validator: city, trigger: 'change'}
        ]
      },
      cityBoole: false
    };
  },
  created() {
    this.handleSumPrice()
    if (this.detailForm.isLimitCity === 1) {
      this.isBool = true
    }
  },
  mounted() {
  },
  methods: {
    handleSumPrice() {
      let num = 0
      let a = toNumberAdd(Number(this.value.checkCarPrice), Number(this.value.registerPrice))
      num = toNumberAdd(Number(a), Number(this.value.photoMailPrice))
      this.value.sumPrice = this.detailForm.sumPrice = num.toString().match(/^\d+(?:\.\d{0,2})?/)[0] || 0
    },
    changeAmount(str) {

      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/
      if (!msg.test(this.detailForm[str])) {
        this.detailForm[str] = ""
      } else {
        this.detailForm[str] = this.detailForm[str].toString().match(/^\d+(?:\.\d{0,2})?/)[0]
        this.handleSumPrice()

      }
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            this.locateToErr()
            reject();
          }
        });
      });
    },

    locateToErr() {

      this.$nextTick(() => {
        let isError = document.getElementsByClassName('is-error')
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: 'center',
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: 'smooth',
        })
      })
    },

    citySelectionChange(val) {

      if (val.length > 0) {
        this.value.indexBelongCity = val[0].label
        this.value.indexBelongCityId = val[0].value
        this.value.areaName = val[0].parent.label
        this.value.areaNameId = val[0].parent.value
        if (this.isBool) {
          let obj = {
            cityId: this.detailForm.indexBelongCityId,
            type: this.detailForm.isLimitCity
          }
          // this.handleGetInfoByCityIdAndType(obj, 'city')
        }
        this.$nextTick(() => {
          this.$refs.detailForm.clearValidate('indexBelongCity')
        })
      } else {
        this.citySelection = val
        this.value.indexBelongCity = ""
        this.value.indexBelongCityId = ""
        this.value.areaName = ""
        this.value.areaNameId = ""

      }
    },

    handleChange(val) {

      this.value.isLimitCity = val

      if (val === 1) {
        this.isBool = true
        if (this.detailForm.indexBelongCityId) {
          let obj = {
            cityId: this.detailForm.indexBelongCityId,
            type: this.detailForm.isLimitCity
          }
          // this.handleGetInfoByCityIdAndType(obj, 'type')
        }
      }
      if (val === 2) {
        this.isBool = false
        this.$nextTick(() => {
          this.$refs.detailForm.clearValidate('indexBelongCity')
          this.$refs.detailForm.clearValidate('indexType')
          this.$refs.detailForm.clearValidate('payType')
        })
      }
    },

    handleGetInfoByCityIdAndType(obj, val) {
      return
      getInfoByCityIdAndType(obj).then(res => {
        this.cityBoole = res
      }).catch(() => {
        if (val === 'city') {
          this.citySelection = []
          this.value.indexBelongCity = ""
          this.value.indexBelongCityId = ""
          this.value.areaName = ""
          this.value.areaNameId = ""
        }
        if (val === 'type') {
          this.value.isLimitCity = ''
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.box-card {
  font-size: 14px;
  margin-bottom: 16px;
}

.el-form-item {
  width: 70%;
}
</style>


